import { acceptHMRUpdate, defineStore } from "pinia";
import socket from "../utils/socket_io";
import { getFriendChatList, readFriendMsg } from "./../service/chat";
import { useUserStore } from "./user"

export const useChatStore = defineStore({
  id: "chatStore",
  state: () => ({
    showChat: false,
    fullChat: false,
    totalUnread: 0,
    msgUnread: 0,
    newFriendUnread: 0,
    messageList: [],
    groupList: [],
    friendList: [],
    // 新的好友通知列表
    newFriendList: [],
    panelStatus: "",
    currentChat: {},
    currentChatType: "",
  }),
  getters: {
    userInfo () {
      // 獲取用戶信息
      const userStore = useUserStore();
      return userStore.userInfo;
    }
  },
  actions: {
    showChatAction (show = false) {
      this.showChat = show || false;
    },

    fullChatAction (show) {
      this.fullChat = show;
    },

    unreadNumAction (data) {
      const [{ friend_msg_num, group_msg_num, new_friend_num }] = data;
      this.msgUnread = group_msg_num + friend_msg_num;
      this.newFriendUnread = new_friend_num;
      this.totalUnread = new_friend_num + group_msg_num + friend_msg_num;
    },

    totalUnreadAction (num) {
      this.totalUnread = num;
    },

    msgUnreadAction (num) {
      this.msgUnread = num;
    },

    newFriendUnreadAction (num) {
      this.newFriendUnread = num;
    },

    groupListAction (data) {
      this.groupList = data;
    },

    friendListAction (data) {
      this.friendList = data;
    },
    newFriendListAction (data) {
      this.newFriendList = data;
    },
    messageListAction (data) {
      const { groupMessageList, friendMessageList } = data;
      this.messageList = [...groupMessageList, ...friendMessageList].sort(
        (a, b) => {
          return b.message_time - a.message_time;
        }
      );
    },
    panelStatusAction (status) {
      this.panelStatus = status;
    },
    async setCurrentChatAction ({ currentChat, currentChatType }) {
      let itemIdx = -1;
      if (currentChatType === "group") {
        itemIdx = this.messageList.findIndex(
          (item) => item.group_id === currentChat.group_id
        );
      } else if ((currentChatType = "friend")) {
        itemIdx = this.messageList.findIndex(
          (item) => item.user_id === currentChat.user_id
        );
      }
      if (itemIdx == -1) {
        this.messageList.unshift(currentChat);
        itemIdx = 0;
      }
      // if (
      //   !this.messageList[itemIdx].messageList ||
      //   !this.messageList[itemIdx].messageList.length
      // ) {
      if (currentChatType === "group") {
      } else if ((currentChatType === "friend")) {
        socket.emit('readMsg', { from: currentChat.user_id, to: this.userInfo.user_id })
        const data = await getFriendChatList({
          limit: 10,
          size: 1,
          user_id: currentChat.user_id,
        });
        this.messageList[itemIdx].messageList = data.data.result;
        this.messageList[itemIdx].unread = 0
        currentChat.messageList = data.data.result;
        // }
      }
      this.currentChatType = currentChatType;
      this.currentChat = Object.assign({}, currentChat);
    },
    currentChatSendMsg ({ currentChat, from, content, messageType }) {
      this.messageList.map(item => {
        if (currentChat.user_id && (item.user_id === currentChat.user_id)) {
          item.messageList.push({
            status: currentChat.status,
            avatar: currentChat.avatar,
            chat_type: messageType,
            content,
            create_timestamp: currentChat.create_timestamp,
            to: currentChat.user_alias,
            from,
            realname: currentChat.realname
          })
          item.message = content
        }
        if (currentChat.group_id && (item.group_id === currentChat.group_id)) {
          item.messageList.push({

          })
        }
        return item
      })
    },
    async currentChatReceiveMsg (data) {
      const {
        from, create_timestamp, content
      } = data
      let itemIdx = this.messageList.findIndex(
        (item) => item.user_id === from
      );
      if (itemIdx == -1) {
        let friend = this.friendList.find(friend => {
          friend.user_id = from
        })
        if (friend.user_id) {
          this.messageList.unshift(data)
        }
      } else {
        if (!this.messageList[itemIdx].messageList) {
          this.messageList[itemIdx].messageList = []
        }
        this.messageList[itemIdx].messageList.push(data)
        this.messageList[itemIdx].message = content;
        this.messageList[itemIdx].message_time = create_timestamp
        if (this.currentChatType === 'friend' && this.currentChat.user_id === from) {
          await readFriendMsg({ from: from })
        } else {
          this.messageList[itemIdx].unread++;
          this.msgUnread++;
          this.totalUnread++;
        }
      }
    }
  },
  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        key: "chatStore",
        storage: localStorage,
      },
    ],
  },
});
// if (import.meta.hot) {
//   import.meta.hot.accept(acceptHMRUpdate(useChatStore, import.meta.hot));
// }
